package com.promise.jokerdream.ui.components

import android.content.Context
import android.view.View
import androidx.lifecycle.setViewTreeLifecycleOwner
import com.google.android.material.bottomsheet.BottomSheetDialog
import androidx.compose.ui.platform.AbstractComposeView
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionContext
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.findViewTreeViewModelStoreOwner
import androidx.savedstate.findViewTreeSavedStateRegistryOwner
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
import androidx.lifecycle.setViewTreeViewModelStoreOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import android.graphics.drawable.GradientDrawable
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_EXPANDED

/**
 * BottomSheetDialogLayout
 * 继承 AbstractComposeView，window 在创建时传入，content 可以 setContent
 */
class BottomSheetDialogLayout(
    context: Context
) : AbstractComposeView(context) {

    private var content: @Composable () -> Unit by mutableStateOf({})

    override var shouldCreateCompositionOnAttachedToWindow: Boolean = false
        private set

    fun setContent(parent: CompositionContext, content: @Composable () -> Unit) {
        setParentCompositionContext(parent)
        this.content = content
        shouldCreateCompositionOnAttachedToWindow = true
        createComposition()
    }

    @Composable
    override fun Content() {
        content()
    }
}

/**
 * BottomSheetDialog 包装器
 * 继承 BottomSheetDialog 并持有 BottomSheetDialogLayout
 */
class BottomSheetDialogWrapper(
    private val composeView: View,
    context: Context,
    theme: Int = 0,
    topRadius: Float = 16f,
    backgroundColor: Int = 0xFFFFFFFF.toInt(),
    private val onDismiss: (() -> Unit)? = null
) : BottomSheetDialog(context, theme) {
    
    /**
     * 持有的 BottomSheetDialogLayout
     */
    private val bottomSheetDialogLayout: BottomSheetDialogLayout by lazy {
        BottomSheetDialogLayout(context)
    }
    
    init {
        // 设置内容视图为 BottomSheetDialogLayout
        setContentView(bottomSheetDialogLayout)
        
        bottomSheetDialogLayout.setViewTreeLifecycleOwner(composeView.findViewTreeLifecycleOwner())
        bottomSheetDialogLayout.setViewTreeViewModelStoreOwner(composeView.findViewTreeViewModelStoreOwner())
        bottomSheetDialogLayout.setViewTreeOnBackPressedDispatcherOwner(this)
        bottomSheetDialogLayout.setViewTreeSavedStateRegistryOwner(
            composeView.findViewTreeSavedStateRegistryOwner()
        )

        setBehaviorProperties()
        
        // 设置圆角和背景色
        setupRoundedCorners(topRadius, backgroundColor)
        
        // 设置取消监听器，处理点击外部区域的情况
        setOnCancelListener {
            onDismiss?.invoke()
        }
    }
    
    override fun dismiss() {
        super.dismiss()
        onDismiss?.invoke()
    }
    
    /**
     * 设置 BottomSheetBehavior 属性
     */
    private fun setBehaviorProperties() {
        behavior.state = STATE_EXPANDED
        behavior.isFitToContents = true
        behavior.isGestureInsetBottomIgnored = false
    }
    
    /**
     * 设置半浮层上边左右的小圆角和背景色
     */
    private fun setupRoundedCorners(radius: Float, bgColor: Int) {
        // 等待布局完成后再设置圆角
        bottomSheetDialogLayout.post {
            val parent = bottomSheetDialogLayout.parent as? View
            parent?.let { parentView ->
                val drawable = GradientDrawable().apply {
                    // 设置上边左右圆角，下边不设置圆角
                    cornerRadii = floatArrayOf(
                        radius, radius, // 左上角
                        radius, radius, // 右上角
                        0f, 0f,         // 右下角
                        0f, 0f          // 左下角
                    )
                    setColor(bgColor) // 自定义背景色
                }

                parentView.background = drawable
            }
        }
    }

    /**
     * 设置 Compose 内容到 BottomSheetDialogLayout
     */
    fun setContent(
        compositionContext: CompositionContext,
        content: @Composable () -> Unit
    ) {
        bottomSheetDialogLayout.setContent(compositionContext, content)
    }
    
    /**
     * 设置内容视图到 BottomSheetDialogLayout
     */
    fun setContentToBottomSheetLayout(view: View) {
        bottomSheetDialogLayout.removeAllViews()
        bottomSheetDialogLayout.addView(view)
    }
}
